<template>
  <div class="p-4">
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <div class="queryBox">
          <div :class="queryParam.deviceType == '3' ? 'toggleButton2' : 'toggleButton'" @click="deviceTypeChange('3')">机场
          </div>
          <div :class="queryParam.deviceType == '2' ? 'toggleButton2' : 'toggleButton'" @click="deviceTypeChange('2')">飞行器
          </div>
        </div>
      </template>
      <template #toolbar>
        <div class="queryBox">
          <a-button class="addButton" preIcon="ant-design:plus-outlined" @click="handleAdd"> 新增设备 </a-button>
        </div>
        <!-- <a-button @click="() => { trackPlaybackOpen = true }">调试</a-button> -->
        <div class="queryBox">
          <a-space>
            <a-select ref="select" v-model:value="queryParam.deviceState" style="width: 181px" :options="options1"
              @change="handleChange"></a-select>
          </a-space>
        </div>
        <div class="queryBox">
          <a-input style="width: 181px" v-model:value="queryParam.deviceName" @input="InputChange" placeholder="请输入设备名称">
            <template #prefix>
              <search-outlined />
            </template>
          </a-input>
        </div>
      </template>
      <template #state="{ record, text }">
        <!-- deviceType	设备类型 3:机场,1:飞行器,2:遥控器 -->
        <!-- <a-badge :color="text == 0 ? '#f14d54' : '#87d068'" :text="text == 0 ? '离线' : '在线'" /> -->
        <!-- <a-tag :color="['f14d54','#87d068'][text]">{{ ['离线','在线'][text] }}</a-tag> -->
        <div v-if="record.deviceType == 3" class="stateBox" :class="{ 'stateBox2': text == 5 }">{{ ['空闲中', '现场调试', '远程调试',
          '固件升级中', '作业中', '离线'][text] }}</div>
        <div v-if="record.deviceType == 0" class="stateBox" :class="{ 'stateBox2': text == 18 }">{{ ['待机', '起飞准备',
          '起飞准备完毕', '手动飞行', '自动起飞', '航线飞行', '全景拍照',
          '智能跟随', 'ADS-B躲避', '自动返航', '自动降落', '强制降落', '三桨叶降落', '升级中', '未连接', 'APAS', '虚拟摇杆状态', '指令飞行', '离线'][text] }}</div>
        <div v-if="record.deviceType == 2" :class="text == 0 ? 'stateBox2' : 'stateBox'">{{ ['离线', '在线'][text] }}
        </div>
        <!-- <a-badge v-if="record.deviceType == 0" :color="text == 0 || text == 4 ? '#87d068' : '#f14d54'"
          :text="text == 0 || text == 4 ? '在线' : '离线'" /> -->
        <!-- <a-badge v-if="record.deviceType == 1"
          :color="text == 8 || text == 11 || text == 12 || text == 13 || text == 14 ? '#87d068' : '#f14d54'"
          :text="text == 8 || text == 11 || text == 12 || text == 13 || text == 14 ? '在线' : '离线'" />
        <a-badge v-if="record.deviceType == 2" :color="['#87d068', '#f14d54'][text]" :text="['在线', '离线'][text]" /> -->
      </template>
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getMore(record)" />
      </template>
    </BasicTable>
    <AddModal @register="registerModal" @success="okSuccess"></AddModal>
    <playbackModal @register="registerPlaybackModal"></playbackModal>
    <journalModal @register="registerjournalModal"></journalModal>
    <equipModal :open="equipModalOpen" :navEquipId="navEquipId" :deviceSn="deviceSn" :deviceId="deviceId"
      @close="() => { equipModalOpen = false }"></equipModal>
    <trackPlaybackModal :open="trackPlaybackOpen" :trackPlaybackDeviceSn="trackPlaybackDeviceSn"
      @close="() => { trackPlaybackOpen = false }"></trackPlaybackModal>
  </div>
</template>
<script lang="ts" setup>
import { ref, watch, reactive, toRaw } from 'vue';
import { BasicTable, TableAction } from '/@/components/Table';
import { columns } from './data';
import type { ActionItem } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage';
import { SearchOutlined } from '@ant-design/icons-vue';
import { useModal } from '/@/components/Modal';
import AddModal from './AddModal.vue';
import playbackModal from './playbackModal.vue';
import journalModal from './journalModal.vue';
import equipModal from './equipModal.vue';
import trackPlaybackModal from '../../components/flightPathReplay/trackPlaybackModal.vue';
import { deviceApi } from './data.api';
import { message } from 'ant-design-vue';

let equipModalOpen = ref(false);
// const deviceName = ref('');

let trackPlaybackOpen = ref<boolean>(false); //轨迹回放弹窗

let queryParam = reactive({
  deviceName: '',
  deviceType: '3',
  deviceState: ''
});

let deviceId = ref(); //设备ID
let navEquipId = ref() //无人机设备ID
let deviceSn = ref(['', '']) //设备SN

let trackPlaybackDeviceSn = ref() // 轨迹回放设备SN

const { tableContext } = useListPage({
  designScope: 'deviceManageList',
  tableProps: {
    api: deviceApi.list,
    isTreeTable: true, // 开启树形表格
    bordered: false,
    striped: true,//斑马纹设置
    columns: columns,
    useSearchForm: false,
    // dataSource: getTreeTableData(),
    childrenColumnName: 'deviceList',
    rowKey: 'id',
    scroll: { x: 1300, y: 1000 },
    tableSetting: {
      redo: false,
      size: false,
      setting: false,
      fullScreen: false,
    },
    defaultSortFn: (sortInfo) => {
      //update-begin-author:taoyan date:2022-10-21 for: VUEN-2199【表单设计器】多字段排序
      if (sortInfo instanceof Array) {
        console.log('sortInfo', sortInfo)

      } else {

        return info || {}
      }
      //update-end-author:taoyan date:2022-10-21 for: VUEN-2199【表单设计器】多字段排序
    },
    searchInfo: {
      deviceType: queryParam.deviceType,
    },
    onChange: (pagination, filters, sorter) => {
      tableSort(sorter)
    },

    // customRow: (columns, index) => {
    //   console.log(columns, index)
    // }
    // fetchSetting: {
    //   deviceName: deviceName
    // }
  }
})
const options1 = ref<SelectProps['options']>([
  {
    value: '',
    label: '全部状态',
  },
  {
    value: '1',
    label: '在线状态',
  },
  {
    value: '0',
    label: '离线状态',
  },
]);
const [registerTable, { reload, setProps, getColumns }, { rowSelection, selectedRows, selectedRowKeys }] = tableContext;
let timer: ReturnType<typeof setTimeout>;
function InputChange(e) {
  queryParam.deviceName = e.target.value;
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(() => {
    // setProps({ deviceName: e.target.value });
    searchQuery()
    // reload()
  }, 500);
}

async function deviceTypeChange(type) {
  queryParam.deviceType = await type
  searchQuery()
}

function searchQuery() {
  setProps({ searchInfo: toRaw(queryParam) });
  reload()
}

const [registerModal, { openModal }] = useModal()
const [registerPlaybackModal, { openModal: openPlaybackModal }] = useModal()
const [registerjournalModal, { openModal: openJournalModal }] = useModal()


function handleAdd() {
  openModal(true, { isUpdate: false })
}

function handleChange() {
  searchQuery()
}

function overButton(record: Object, type: String) {
  console.log(record, type)
  switch (type) {
    case 'edit':
      openModal(true, { isUpdate: true, record })
      break;
    case 'delete':
      getDelDevice(record)
      console.log('删除')
      break;
    case 'trackPlayback':
      trackPlaybackOpen.value = true
      trackPlaybackDeviceSn.value = record.deviceSn
      // openregistertrackPlaybackModal(true)
      break
    case 'journal':
      openJournalModal(true, { isUpdate: true })
      break;
    case 'equip':
      if (record.state != 5) {
        equipModalOpen.value = true
        deviceId.value = record.deviceId
        navEquipId.value = record.deviceList[0].deviceId
        deviceSn.value[0] = record.deviceSn
        deviceSn.value[1] = record.deviceList[0].deviceSn
      } else {
        message.error('当前设备已离线!');
      }


      break;
    default:
      break
  }
}

async function getDelDevice(record) {
  await deviceApi.del(record.id)
  reload()
}


function getTableAction(record): ActionItem[] {
  return [
    { label: '编辑', onClick: () => overButton(record, 'edit') },
    {
      label: '删除', popConfirm: {
        title: '是否删除？',
        confirm: () => overButton(record, 'delete'),
      },
    },
  ]
}

function getMore(record) {
  let arr = []

  if (record.deviceType == 3) {
    //机场才有的按钮
    //对频了的无人机的列表归属于对应的机场或遥控器之下，操作栏两行合并成一个
    arr.push({ label: '告警日志', onClick: () => overButton(record, 'journal') }, { label: '设备调试', onClick: () => overButton(record, 'equip') })
  }

  if (record.deviceType == 0) {
    arr.push({ label: '轨迹回放', onClick: () => overButton(record, 'trackPlayback') })
  }
  return arr

}

function okSuccess() {
  reload()
  console.log('okSuccess')
}

function tableSort(sorter) {
  console.log(sorter)
}

// function getTreeTableData() {
//   const data: any = (() => {
//     const arr: any = []
//     for (let i = 0; i < 10; i++) {
//       arr.push({
//         id: `${i}`,
//         k1: `华平测试机场${i}`,
//         k2: `DJl Dock${i}`,
//         k3: `4TAD003132131${i}`,
//         k4: `哈哈哈哈${i}`,
//         k5: `123456789${i}`,
//         k6: `0`,
//         k7: `东莞同沙水库研发部测试项目${i}`,
//         k8: `广东省深圳市龙岗区平湖街道华平科技大厦`,
//         k9: `2023-09-06 11:50:25`,
//         children: [
//           {
//             id: `12-${i}`,
//             k1: `测试机场${i}`,
//             k2: `DJl Dock${i}`,
//             k3: `4TAD003132131${i}`,
//             k4: `哈哈哈哈${i}`,
//             k5: `123456789${i}`,
//             k6: `1`,
//             k7: `东莞同沙水库研发部测试项目${i}`,
//             k8: `广东省深圳市龙岗区平湖街道华平科技大厦`,
//             k9: `2023-09-06 11:50:25`,
//           },
//           {
//             id: `13-${i}`,
//             k1: `测试机场${i}`,
//             k2: `DJl Dock${i}`,
//             k3: `4TAD003132131${i}`,
//             k4: `哈哈哈哈${i}`,
//             k5: `123456789${i}`,
//             k6: `0`,
//             k7: `东莞同沙水库研发部测试项目${i}`,
//             k8: `广东省深圳市龙岗区平湖街道华平科技大厦`,
//             k9: `2023-09-06 11:50:25`,
//           },
//           {
//             id: `14-${i}`,
//             k1: `测试机场${i}`,
//             k2: `DJl Dock${i}`,
//             k3: `4TAD003132131${i}`,
//             k4: `哈哈哈哈${i}`,
//             k5: `123456789${i}`,
//             k6: `1`,
//             k7: `东莞同沙水库研发部测试项目${i}`,
//             k8: `广东省深圳市龙岗区平湖街道华平科技大厦`,
//             k9: `2023-09-06 11:50:25`,
//           }
//         ]
//       })
//     }
//     return arr;
//   })();
//   return data

// }

</script>
<style lang="less" scoped>
/deep/ .jeecg-basic-table-header__table-title-box {
  border-bottom: 1px solid #f8fafb;
}

/deep/ .ant-table-thead>tr>th {
  background: #edf6fb;
  color: #0F699A;
}

/deep/ .jeecg-basic-table-row__striped>td {
  background-color: #f7fbfc;
}

/deep/ .ant-table-tbody>tr.ant-table-row:hover>td,
.ant-table-tbody>tr>td.ant-table-cell-row-hover {
  background: #eef6fa;
}

.stateBox {
  padding: 1px 9px;
  background-color: #e7f7f1;
  color: #15B37A;
  font-size: 12px;
  display: inline-block;
}

.stateBox2 {
  padding: 1px 9px;
  background-color: #e5ecf0;
  color: #999999;
  font-size: 12px;
  display: inline-block;
}

.buttonBox {
  padding: 12px 10px 12px 10px;
  margin-bottom: 8px;
  background-color: #fff;
  border-radius: 2px;
}

.queryBox {
  margin-right: 12px;
  margin-bottom: 0px;

  .toggleButton {
    width: 115px;
    height: 47px;
    // background-color: red;
    display: inline-block;
    font-size: 14px;
    color: #333333;
    font-weight: 700;
    text-align: center;
    line-height: 46px;
    cursor: pointer;
  }

  .toggleButton2 {
    width: 115px;
    height: 47px;
    // background-color: red;
    display: inline-block;
    font-size: 14px;
    color: #155b81;
    font-weight: 700;
    text-align: center;
    line-height: 46px;
    border-bottom: 2px solid #155b81;
    cursor: pointer;
  }

  .addButton {
    background: linear-gradient(315deg, #1792D6 0%, #0E6EA1 100%);
    border-radius: 2px;
    color: white;
    border: none;
  }

}
</style>
